package com.lzx.iteam.widgetview;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Switch;
import android.widget.Toast;
import com.lzx.iteam.DialerApp;
import com.lzx.iteam.MainActivity;
import com.lzx.iteam.R;
import com.lzx.iteam.ScheduleCalendarActivity;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetCalendarMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.DateUtil;
import com.lzx.iteam.util.PreferenceUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 04月 06日
 * Time: 上午10:41
 *
 * @QQ : 1234567890
 * **********************************
 */
public class WidgetSetProvider extends AppWidgetProvider {

    public final static String CLICK_ACTION = "com.stone.action.clickset";
    public final static String CLICK_ITEM_ACTION = "com.stone.action.clickset.item";
    public final static String EXTRA_ITEM = "extra_item";
    private static final int GET_LIST = 10001;

    private String mUid;
    private RemoteViews mRemoteViews;
    private AppWidgetManager mAppWidgetManager;
    private int mAppWidgetId;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET_LIST:
                    // TODO 刷新数据 刷新页面
                    Log.d("onReceive_widget", " ===  handleMessage ======");
                    mRemoteViews.setViewVisibility(R.id.widget_progress, View.GONE);
                    mRemoteViews.setViewVisibility(R.id.widget_iv, View.VISIBLE);
                    mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews);
                    mAppWidgetManager.notifyAppWidgetViewDataChanged(mAppWidgetId, R.id.widget_lv);
                    if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                        Toast.makeText(DialerApp.mContext, R.string.active_failure_no_network,
                                Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        Log.d("onReceive_widget", " ===  onReceive ======");

        String action = intent.getAction();
        if (action.equals(CLICK_ACTION)) {
            int position = intent.getIntExtra("position", -1);
            if (position != -1) {
                // listvie点击回来在这里处理
                Log.d("onReceive_widget", "position == " + position);
            } else {
                Log.d("onReceive_widget", " ===  CLICK_ACTION ======");
                mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_view);
                mAppWidgetManager = AppWidgetManager.getInstance(context);
                mAppWidgetId = intent.getIntExtra("appWidgetId", 1);

                // TODO 显示 progressbar
                mRemoteViews.setViewVisibility(R.id.widget_progress, View.VISIBLE);
                mRemoteViews.setViewVisibility(R.id.widget_iv, View.GONE);
                mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews);

                Calendar calendar = Calendar.getInstance();
                int curYear = calendar.get(Calendar.YEAR);
                int curMonth = calendar.get(Calendar.MONTH) + 1; //通过Calendar算出的月数要+1
                int curDate = calendar.get(Calendar.DATE);
                mUid = PreferenceUtil.getInstance(context).getString(PreferenceUtil.CLIENT_USEID, "－1");
                getCalendarData(curYear+"",curMonth+"",curDate+"",context);

            }
        }

    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        updateWidget(context, appWidgetManager, appWidgetIds);
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    @Override
    public void onAppWidgetOptionsChanged(Context context,
                                          AppWidgetManager appWidgetManager, int appWidgetId,
                                          Bundle newOptions) {
        super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId,
                newOptions);
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    }

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
    }

    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
    }

    private void updateWidget(Context context, AppWidgetManager awm, int[] appWidgetIds) {

        for (int appWidgetId : appWidgetIds) {

            // TODO 填充listview数据
            Intent intent = new Intent(context, WidgetSetService.class);
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_view);
            views.setRemoteAdapter(R.id.widget_lv, intent);
            views.setTextViewText(R.id.widget_tv_time, DateUtil.formatDate(System.currentTimeMillis()));

            // TODO 刷新数据
            Intent pendIntent = new Intent(CLICK_ACTION);
            pendIntent.putExtra("appWidgetId", appWidgetId);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, pendIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
//            点击按钮将触发广播，当前接收器将即时接收和处理广播消息
            views.setOnClickPendingIntent(R.id.widget_iv, pendingIntent);

//            views.setPendingIntentTemplate(R.id.widget_lv, pendingIntent);

            // TODO 进入日程页面
            Intent activity = new Intent(context, ScheduleCalendarActivity.class);
            //创建一个pendingIntent。另外两个参数以后再讲。
            PendingIntent pendingAc = PendingIntent.getActivity(
                    context, 0, activity, 0);
            //创建一个remoteViews。
//            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_view);
            //绑定处理器，表示控件单击后，会启动pendingIntent。
            views.setOnClickPendingIntent(R.id.widget_title, pendingAc);
            awm.updateAppWidget(appWidgetId, views);

            Log.d("onReceive_widget", " ===  updateWidget ======");
        }

    }

    /**
     * 获取日历列表 和 日程列表
     * @param year
     * @param month
     * @param day
     */
    public void getCalendarData(String year,String month,String day,Context context){

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CALENDAR_DATE,year + "_" +month));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CALENDAR_DAY,day+""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CALENDAR_BOSS_UID,mUid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));

        GetCalendarMsg msg = new GetCalendarMsg(mHandler.obtainMessage(GET_LIST),context,year,month,day,mUid);
        msg.mParams = nvps;
        msg.mApi = AsynHttpClient.API_EVENT_CALENDAR_LIST;
        AsynHttpClient.getInstance(context).execEventHttp(msg);

    }

}
